import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'
import { useAuthStore } from './auth'

export const useTodoStore = defineStore('todo', () => {
  const todos = ref([])
  const loading = ref(false)
  const error = ref(null)

  const fetchTodos = async () => {
    try {
      loading.value = true
      const authStore = useAuthStore()
      const response = await axios.get('/api/todos', {
        headers: {
          Authorization: `Bearer ${authStore.token}`
        }
      })
      todos.value = response.data
    } catch (err) {
      error.value = err.response.data
    } finally {
      loading.value = false
    }
  }

  const addTodo = async (todo) => {
    try {
      const authStore = useAuthStore()
      const response = await axios.post('/api/todos', todo, {
        headers: {
          Authorization: `Bearer ${authStore.token}`
        }
      })
      todos.value.push(response.data)
    } catch (err) {
      throw err.response.data
    }
  }

  const updateTodo = async (id, updates) => {
    try {
      const authStore = useAuthStore()
      const response = await axios.put(`/api/todos/${id}`, updates, {
        headers: {
          Authorization: `Bearer ${authStore.token}`
        }
      })
      const index = todos.value.findIndex(t => t.id === id)
      if (index !== -1) {
        todos.value[index] = response.data
      }
    } catch (err) {
      throw err.response.data
    }
  }

  const deleteTodo = async (id) => {
    try {
      const authStore = useAuthStore()
      await axios.delete(`/api/todos/${id}`, {
        headers: {
          Authorization: `Bearer ${authStore.token}`
        }
      })
      todos.value = todos.value.filter(t => t.id !== id)
    } catch (err) {
      throw err.response.data
    }
  }

  return {
    todos,
    loading,
    error,
    fetchTodos,
    addTodo,
    updateTodo,
    deleteTodo
  }
})
